package com.lzy.service.impl;

import com.lzy.NotFoundException;
import com.lzy.dao.TypeRepository;
import com.lzy.po.Type;
import com.lzy.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @autor shkstart
 * @create 2021-01-05 22:55)
 */
@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository typeRepository;

    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        /*
        *  springboot1.5x 使用findOne(id)
        *
        *  spingBoot2.0x 使用  findById(id).get();
        */
        return typeRepository.findById(id).get();
    }

    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Type t = typeRepository.findById(id).get();
        if(t == null){
            throw new NotFoundException();
        }
        BeanUtils.copyProperties(type,t);

        /*
        * 调用save方法可能有两种情况
        若db中这个id对应的字段不存在，则插入
        若db中这个id对应的字段存在，则更新
        * */
        return typeRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);
    }


    //查询首页分类显示的条数
    @Override
    public List<Type> listType(Integer size) {
        Sort.Order sort = new Sort.Order(Sort.Direction.DESC,"blogs.size"); //根据类型中的博客数排序
        Pageable pageable = PageRequest.of(0,size,Sort.by(sort)); //只显示第一页
        return typeRepository.findTop(pageable);
    }
}
